package cn.maihe.elg.operation.service.business;

import cn.maihe.elg.operation.model.enums.InstitutionCode;
import cn.maihe.elg.operation.model.vo.business.InstitutionUserVO;
import cn.maihe.elg.operation.repository.entity.GuaranteeInstitutionDO;
import cn.maihe.elg.operation.repository.entity.GuaranteeInstitutionDOCondition;
import cn.maihe.elg.operation.repository.entity.GuaranteeInstitutionVo;
import cn.maihe.elg.operation.service.BaseDaoService;
import cn.maihe.framework.starter.base.sql.PageBo;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Description 出函机构服务
 * @Author WJH
 * @Date 2021/03/25
 */
@Service
public class InstitutionService extends BaseDaoService<GuaranteeInstitutionDO> {


    public PageBo<GuaranteeInstitutionDO> selectPageBySql(int pageNo, int pageSize, GuaranteeInstitutionVo vo) {
        Map<String, Object> paramsMap = toMapAndAddParams(vo);
        return this.selectPageBySql("selectInstitutionList", "selectInstitutionCount", paramsMap, pageNo, pageSize);
    }

    /**
     * 是否存在 用户-出函机构 关联记录
     *
     * @param id
     * @return
     */
    public boolean existsInstitutionLinkedUser(Long id) {
        Map<String, Object> paramsMap = Maps.newHashMap();
        paramsMap.put("id", id);
        return this.selectCountBySql("institutionLinkedUserCount", paramsMap) > 0;
    }

    public List<InstitutionUserVO> getOrgInstitution(Long userId) {
        Map<String, Object> paramsMap = Maps.newHashMap();
        paramsMap.put("userId", userId);
        return this.selectListBySql("orgInstitutionList", paramsMap);
    }

    public List<InstitutionUserVO> getAccountInstitution(Long userId, Long orgUserId) {
        Map<String, Object> paramsMap = Maps.newHashMap();
        paramsMap.put("userId", userId);
        paramsMap.put("orgUserId", orgUserId);
        return this.selectListBySql("accountInstitutionList", paramsMap);
    }

    public GuaranteeInstitutionDO getInstitutionByAcceptOrderNo(String acceptOrderNo) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("acceptOrderNo", acceptOrderNo);
        return this.selectOneBySql("getInstitutionByAcceptOrderNo", params);
    }

    public InstitutionCode getInstitutionCode(String acceptOrderNo) {
        GuaranteeInstitutionDO institutionDO = this.getInstitutionByAcceptOrderNo(acceptOrderNo);
        InstitutionCode institutionCode = InstitutionCode.resolve(institutionDO.getInstitutionCode());
        if(institutionCode==null){
            throw new RuntimeException("暂未实现该出函机构[" + institutionDO.getInstitutionCode() + "]相关业务");
        }
        return institutionCode;
    }

    public GuaranteeInstitutionDO getInstitutionByCode(String code){
        return this.selectOne(GuaranteeInstitutionDOCondition.builder().andInstitutionCodeEq(code).build());
    }


}
